package com.liuqianfei.markme.rules.block;

import com.liuqianfei.markme.core.Token;
import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.IAction;

import java.util.ArrayList;
import java.util.List;

/**
 * Paragraph
 * @author liuqianfei
 */
public class ParagraphAction implements IAction
{
    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine_para)
    {
        String content;
        boolean terminate;
        int i;
        int l;
        Token token;
        String oldParentType;
        int nextLine = startLine + 1;
        List<IAction> terminatorRules = state.getMd().parserBlock.ruler.getRules("paragraph");
        int endLine = state.getLineMax();

        oldParentType = state.getParentType();
        state.setParentType("paragraph");

        // jump line-by-line until empty one or EOF
        for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++)
        {
            // this would be a code block normally, but after paragraph
            // it's considered a lazy continuation regardless of what's there
            if (state.getsCount(nextLine) - state.getBlkIndent() > 3)
                continue;

            // quirk for blockquotes, this line should already be checked by that rule
            if (state.getsCount(nextLine) < 0)
                continue;

            // Some tags can terminate paragraph without empty line.
            terminate = false;
            for (i = 0, l = terminatorRules.size(); i < l; i++)
            {
                if (terminatorRules.get(i).parse(state, true, nextLine, endLine))
                {
                    terminate = true;
                    break;
                }
            }
            if (terminate)
                break;
        }

        content = state.getLines(startLine, nextLine, state.getBlkIndent(), false).trim();

        state.setLine(nextLine);

        token          = state.push("paragraph_open", "p", 1);
        token.map      = new int[]{startLine, state.getLine()};

        token          = state.push("inline", "", 0);
        token.content  = content;
        token.map      = new int[]{startLine, state.getLine()};
        token.children = new ArrayList<>();

        token          = state.push("paragraph_close", "p", -1);

        state.setParentType(oldParentType);

        return true;
    }
}
